"""
分镜/镜头规划服务
"""
from typing import List, Optional
from loguru import logger

from storyforge.models import Shot, ShotPlan, Episode
from storyforge.utils import get_project_dir, load_json, save_json, generate_id


class ShotsService:
    """分镜服务"""
    
    def __init__(self):
        """初始化服务"""
        from storyforge.config import get_config
        self.config = get_config()
    
    def plan_shots(
        self,
        project_name: str,
        episode_index: int,
        template: str = "default"
    ) -> List[Shot]:
        """
        为剧集规划分镜/镜头
        
        Args:
            project_name: 项目名称
            episode_index: 剧集序号
            template: 模板名称
            
        Returns:
            Shot列表
        """
        project_dir = get_project_dir(project_name, self.config.paths.projects)
        episode_file = project_dir / f"episode_{episode_index}.json"
        
        episode_data = load_json(str(episode_file))
        if not episode_data:
            raise FileNotFoundError(f"剧集文件不存在: {episode_file}")
        
        episode = Episode(**episode_data)
        
        logger.info(f"规划第{episode_index}集的分镜，模板: {template}")
        
        shots = []
        
        # 从剧本JSON中提取场景信息
        script_json = episode.scriptJSON
        scenes = script_json.get("scenes", [])
        
        if not scenes:
            # 如果没有场景，从beats生成
            beats = script_json.get("beats", [])
            for beat_idx, beat in enumerate(beats):
                shot_plan = ShotPlan(
                    shotIndex=beat_idx + 1,
                    sceneType=beat.get("type", "setup"),
                    framing="medium-shot",
                    duration=beat.get("durationHint", 30.0),
                    elements=[beat.get("hook", "")],
                    dialogue=None
                )
                
                shot = Shot(
                    id=generate_id(f"shot_{episode_index}_{beat_idx + 1}_"),
                    episodeId=episode.id,
                    index=beat_idx + 1,
                    shotPlan=shot_plan,
                    duration=shot_plan.duration
                )
                
                shots.append(shot)
        else:
            # 从场景生成镜头
            shot_idx = 1
            for scene in scenes:
                shot_plan = ShotPlan(
                    shotIndex=shot_idx,
                    sceneType=scene.get("sceneType", "dialogue"),
                    framing=scene.get("framing", "medium-shot"),
                    duration=scene.get("duration", 30.0),
                    elements=scene.get("elements", []),
                    dialogue=scene.get("dialogue")
                )
                
                shot = Shot(
                    id=generate_id(f"shot_{episode_index}_{shot_idx}_"),
                    episodeId=episode.id,
                    index=shot_idx,
                    shotPlan=shot_plan,
                    duration=shot_plan.duration
                )
                
                shots.append(shot)
                shot_idx += 1
        
        # 保存镜头计划
        shots_file = project_dir / f"episode_{episode_index}_shots.json"
        save_json({"shots": [shot.dict() for shot in shots]}, str(shots_file))
        
        logger.info(f"已规划 {len(shots)} 个镜头")
        return shots

